//============================================================================
// Name        : Main.cpp
// Author      : David Kadlecek, Ales Fiser
// Version     :
// Copyright   : Your copyright notice
// Description : sequntialClique in C++, Ansi-style
//============================================================================

#include "InputMatrixHolder.h"
#include "Tests.h"
#include "ParallelCore.h"
#include "mpi.h"
#include <time.h>
#include <time.h>

#include "general.h"

using namespace std;

int my_rank1;
int p_count1;

void runMain(string fileName, double r_p) {
	InputMatrixHolder* inputMatrix = new InputMatrixHolder();
	inputMatrix->readFromFile(fileName);
	ParallelCore* parCore = new ParallelCore();
	parCore->loadInputMatrix(inputMatrix);
	int16_t* result;
	result = parCore->doParallel(r_p);

	if (my_rank1 == 0 || logResultsFromAllJobs) {
		//print
		int size = 0;
		cout << my_rank1 << " solution ";
		for (int i = 0; i < inputMatrix->getNumberOfNodes(); ++i) {
			if (result[i] > 0) {
				cout << result[i] << " ";
				size++;
			}
		}
		cout << "|solution size is " << size << " |";
		if (r_p * (float) inputMatrix->getNumberOfNodes() <= size) {
			cout << " which is correct" << endl;
		} else {
			cout << " which is not correct" << endl;
		}
	}
	delete parCore;
}

void doTests() {
	Tests* test = new Tests();
	test->runTests();
	delete test;
}

int main(int argc, char *argv[]) {
	double r_p = 0;
	time_t secondsStart, secondsEnd, diff;

	MPI_Init(&argc, &argv);
	MPI_Comm_size(MPI_COMM_WORLD, &p_count1);
	MPI_Comm_rank(MPI_COMM_WORLD, &my_rank1);

	if (my_rank1 == 0) {
		secondsStart = time(NULL);
		printf("started %ld seconds since January 1, 1970 \n", secondsStart);
	}

	string fileName;
	if (argc >= 2) {
		fileName = string(argv[1]);
		std::istringstream stm;
		stm.str(string(argv[2]));
		stm >> r_p;
//		r_p = r;
	} else {
		fileName = fileInput;
		r_p = r;
	}

	if (my_rank1 == 0) {
		cout << fileName << endl;
	}

	if (runTestCode) {
		doTests();
	} else {
		runMain(fileName, r_p);
	}
	if (logFinalize) cout << my_rank1 << " start finalize" << endl;

	MPI_Finalize();
	if (logFinalize) cout << my_rank1 << " end finalize" << endl;

	if (my_rank1 == 0) {
		secondsEnd = time(NULL);
		diff = secondsEnd - secondsStart;
		printf("enddedd %ld seconds since January 1, 1970,  diference is %ld seconds, it is %ld min and %ld sec\n", secondsEnd, diff, diff / 60, diff % 60);
		cout << "used processors: " << p_count1 << endl;
	}

	return 0;
}

